import React, { useState, useEffect } from "react";
import { UserOutlined } from "@ant-design/icons";
import "./teacher-list.css";
import { Button, Table, Modal, Avatar, Popconfirm, Pagination } from "antd";
import { Link } from "react-router-dom";
import axios from "axios";
import TeacherForm from "../TeacherForm";
import teacherService from "../../services/teacherService";

export default function TeacherList(props) {
  const [teachers, setTeachers] = useState([]);
  const [updVal, setUpdVal] = useState({});
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [count, setCount] = useState(0);

  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  const [isUpdModalVisible, setIsUpdModalVisible] = useState(false);

  //CURD - 查询数据
  useEffect(() => {
    queryTeachers();
  }, [currentPage, pageSize]);

  const queryTeachers = async () => {
    let queryParam = {};
    queryParam["currentPage"] = currentPage;
    queryParam["pageSize"] = pageSize;
    const response = await teacherService.queryTeachers(queryParam);
    setTeachers(response.data.data);
    setCount(response.data.total);
  };

  //CURD - 删除数据
  const handleDelete = async (item) => {
    await teacherService.delete(item.id);
    await queryTeachers();
  };

  //CURD - 创建数据
  const handleAdd = async (values) => {
    await teacherService.create(values);
    setCurrentPage(1);
    queryTeachers();
  };

  const updArrayByItem = (arr, item) => {
    const newArr = arr.map((arrItem) => {
      if (arrItem.id === item.id) return item;
      else return arrItem;
    });
    return newArr;
  };

  //CURD - 编辑数据
  const handleUpdate = async (item) => {
    item["id"] = updVal.id;
    await axios.put(`http://localhost:8080/teachers/${item.id}`, item);
    const newTeachers = updArrayByItem([...teachers], item);
    setTeachers(newTeachers);
  };

  const handleChange = (currentPage, pageSize) => {
    setCurrentPage(currentPage);
    setPageSize(pageSize);
  };

  const handleSizeChange = (pageSize) => {
    setCurrentPage(1);
    setPageSize(pageSize);
  };

  //打开编辑Modal
  const onUpdClick = (item) => {
    setIsUpdModalVisible(true);
    setUpdVal(item);
    console.log(item);
  };

  const onAddSubmit = () => {
    setIsAddModalVisible(false);
  };

  const onUpdSubmit = () => {
    setIsUpdModalVisible(false);
  };

  const columns = [
    {
      title: "行号",
      dataIndex: "行号",
      key: "id",
      render: (_, record, index) => `${index + 1}`,
    },
    {
      title: "头像",
      dataIndex: "avatar",
      key: "avatar",
      render: (_, index) => {
        return (
          <Link to={`/profile/${index.id}`}>
            <Avatar
              style={{
                backgroundColor: "#87d068",
              }}
              icon={<UserOutlined />}
            />
          </Link>
        );
      },
    },
    { title: "姓名", dataIndex: "name", key: "name" },
    {
      title: "性别",
      dataIndex: "gender",
      key: "gender",
      render: (_, record, index) => {
        return record.gender === 1 ? "男" : "女";
      },
    },
    { title: "手机号", dataIndex: "phone", key: "phone" },
    { title: "邮箱", dataIndex: "email", key: "email" },
    { title: "描述", dataIndex: "description", key: "description" },
    {
      title: "操作",
      dataIndex: "operation",
      key: "operation",
      render: (_, record, index) =>
        teachers.length >= 1 ? (
          <div className="del-update-container">
            <Button
              type="primary"
              size="small"
              onClick={() => onUpdClick(record)}
            >
              修改
            </Button>
            <Popconfirm
              title="确认删除此行吗？"
              okText="确认"
              cancelText="取消"
              onConfirm={() => handleDelete(record)}
            >
              <Button type="primary" danger size="small">
                删除
              </Button>
            </Popconfirm>
          </div>
        ) : null,
    },
  ];
  return (
    <div className="teacher-list">
      <div className="add-search-container">
        <Button type="primary" onClick={() => setIsAddModalVisible(true)}>
          Add New
        </Button>
      </div>
      <Modal
        style={{ display: "flex", justifyContent: "center" }}
        title={"新增一位教师"}
        open={isAddModalVisible}
        destroyOnClose={true}
        footer={[]}
        onCancel={() => setIsAddModalVisible(false)}
      >
        <TeacherForm handleAdd={handleAdd} onAddSubmit={onAddSubmit} />
      </Modal>
      <Modal
        style={{ display: "flex", justifyContent: "center" }}
        open={isUpdModalVisible}
        title={"编辑一位教师"}
        destroyOnClose={true}
        footer={[]}
        onCancel={() => setIsUpdModalVisible(false)}
      >
        <TeacherForm
          values={updVal}
          handleUpdate={handleUpdate}
          onUpdSubmit={onUpdSubmit}
        />
      </Modal>
      <Table
        columns={columns}
        rowKey={(record) => {
          return record.id;
        }}
        dataSource={teachers}
        pagination={false}
      />
      <Pagination
        className="ant-pagination-float-right"
        current={currentPage}
        onChange={handleChange}
        onShowSizeChange={handleSizeChange}
        total={count}
      />
    </div>
  );
}
